﻿using System;
using System.Diagnostics;

namespace MikeKappel.Com.CS
{
    public static partial class SortingAlgorithms
    {
        public delegate Boolean CocktailDelegate(Int32 currentIndex, Int32 currentValue);

        public static void CocktailSort(CocktailDelegate onSort, Int32[] items)
        {
            Int32 temp = 0;
            Int32 exchange = 0;
            Int32 j = 0;
            do
            {
                exchange = 0;
                for (j = (items.Length) - 1; j > 0; --j)
                {
                    if ((Int32)items.GetValue(j - 1) > (Int32)items.GetValue(j))
                    {
                        temp = (int)items.GetValue(j - 1);
                        items.SetValue(items.GetValue(j), j - 1);
                        items.SetValue(temp, j);
                        exchange = 1;
                        if (onSort != null && !onSort(j, items[j]))
                                goto escape;
                    }
                }

                for (j = 1; j < items.Length; ++j)
                {
                    if ((Int32)items.GetValue(j - 1) > (Int32)items.GetValue(j))
                    {
                        temp = (Int32)items.GetValue(j - 1);
                        items.SetValue(items.GetValue(j), j - 1);
                        items.SetValue(temp, j);
                        exchange = 1;
                        if (onSort != null && !onSort(j, items[j]))
                                goto escape;
                    }
                }

            } while (Convert.ToBoolean(exchange));

        escape:
            return;
        }
        public static void CocktailSort(Int32[] items)
        {
            CocktailSort(null, items);
        }
    }
}
